//
//  JMColorView.m
//  YaoYao
//
//  Created by JM Zhao on 2017/5/2.
//  Copyright © 2017年 JunMingZhaoPra. All rights reserved.
//

#import "JMColorView.h"
#import "UIImage+JMImage.h"
#import "UIView+Extension.h"
#import "JMMacro.h"
#import "StaticClass.h"

@interface JMColorView ()
@property (nonatomic, weak) UIImageView *colorSelectImage;
@property (nonatomic, weak) UIImageView *point;
@end

@implementation JMColorView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        UIImageView *point = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"point.png"]];
        [self addSubview:point];
        self.point = point;
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
    CGFloat chassRadius = self.width/2-10;
    CGFloat absDistanceX = fabs(currentPoint.x - self.width/2);
    CGFloat absDistanceY = fabs(currentPoint.y - self.height/2);
    CGFloat currentToPointRadius = sqrtf(absDistanceX *absDistanceX + absDistanceY *absDistanceY);
    
    if (currentToPointRadius < chassRadius) {
        self.point.center = currentPoint;
        UIColor *color = [self colorOfPoint:currentPoint];
        if (self.colorBlock && color) {self.colorBlock(color);}
    }
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
    CGFloat chassisRadius = self.width/2-10;
    CGFloat absDistanceX = (currentPoint.x - self.width/2);
    CGFloat absDistanceY = (currentPoint.y - self.height/2);
    CGFloat currentTopointRadius = sqrtf(absDistanceX * absDistanceX + absDistanceY *absDistanceY);
    
    if (currentTopointRadius < chassisRadius) {
        
        // 取色
        self.point.center = currentPoint;
        UIColor *color = [self colorOfPoint:currentPoint];
        if (self.colorBlock && color) {self.colorBlock(color);}
    }
}

- (UIColor *)getPixelColorAtLocation:(CGPoint)point
{
    UIColor *color = nil;
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRef inImage = viewImage.CGImage;
    
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    if (cgctx == NULL) {
        return nil;
    }
    
    size_t w = self.bounds.size.width;
    size_t h = self.bounds.size.height;
    
    CGRect rect = {{0,0},{w,h}};
    CGContextDrawImage(cgctx, rect, inImage);
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        int offset = 4*((w*round(point.y))+round(point.x));
        int alpha =  data[offset];
        int red = data[offset+1];
        int green = data[offset+2];
        int blue = data[offset+3];
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
    }
    CGContextRelease(cgctx);
    if (data) { free(data); }
    return color;
}

- (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {
    
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    void * bitmapData;
    int bitmapByteCount;
    int bitmapBytesPerRow;
    
    size_t pixelsWide = self.bounds.size.width;
    size_t pixelsHigh = self.bounds.size.height;
    
    bitmapBytesPerRow = (int)(pixelsWide * 4);
    bitmapByteCount = (int)(bitmapBytesPerRow * pixelsHigh);
    
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL){
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }
    
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL){
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
    context = CGBitmapContextCreate (bitmapData,pixelsWide,pixelsHigh,8, bitmapBytesPerRow,
                                     colorSpace,kCGImageAlphaPremultipliedFirst);
    if (context == NULL){
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }
    CGColorSpaceRelease( colorSpace );
    return context;
}

- (UIColor *)colorOfPoint:(CGPoint)point
{
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1,1,8,4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    CGContextTranslateCTM(context, -point.x, -point.y);
    [self.layer renderInContext:context];
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    return color;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _point.frame = CGRectMake(100, 100, 30, 30);
}

- (void)drawRect:(CGRect)rect {

    UIImage *centerImage = [UIImage imageNamed:@"ColorPalette.png"];
    [centerImage drawInRect:self.bounds];
}

- (void)dealloc
{
#ifdef DEBUG
    NSLog(@"JMColorView销毁 %s", __FUNCTION__);
#endif
}


@end
